<?php
/**
 * | 节程 [ 节程赋能开发者，助力企业发展 ]
 * +----------------------------------------------------------------------
 *  | Copyright (c) 2020~2029 温州惊蛰网络科技有限公司 All rights reserved.
 * +----------------------------------------------------------------------
 *  | Licensed 节程并不是自由软件，未经许可不能去掉节程相关版权
 * +----------------------------------------------------------------------
 */


namespace app\command;

use think\console\Input;
use think\console\Output;
use think\Exception;
use think\facade\Db;
use app\madmin\model\Agent;

class AgentUpgrade extends BaseCommand
{
    protected function configure()
    {
        // 指令配置
        $this->setName('agent_upgrade')
            ->setDescription('分销商升级');
    }

    protected function execute(Input $input, Output $output)
    {
        $this->setDb($input, $output);
    }


    private function commodity($config,$mall_id): void
    {
        $commodity = $config->become->condition->buyCommodity->commodity;
        $order = Db::name('order')
            ->field('user_id')
            ->where('mall_id',$mall_id)
            ->where('user_id', 'NOT IN', function ($sql) {
                $sql->name('user')
                    ->field('id')
                    ->where('agent_id', 'NOT NULL')
                    ->where('agent_id', '>', 0);
            })
            ->where('id', 'IN', function ($sql) use ($commodity) {
                $sql->name('order_commodity')
                    ->field('order_id')
                    ->where('commodity_id', 'IN', $commodity);
            })
            ->where('status', 4)
            ->group('user_id')
            ->select();
        foreach ($order as $key => $value) {
            $this->userToAgent($config,$value['user_id']);
        }
    }


    private function money($config,$mall_id): void
    {
        $order = Db::name('order')
            ->field('user_id,sum(money) AS money')
            ->where('mall_id',$mall_id)
            ->where('user_id', 'NOT IN', function ($sql) {
                $sql->name('user')
                    ->field('id')
                    ->where('agent_id', 'NOT NULL')
                    ->where('agent_id', '>', 0);
            })
            ->where('status', 4)
            ->group('user_id')
            ->select();
        foreach ($order as $key => $value) {
            if ($value['money'] < $config->become->condition->explainTotal->explain) continue;
            $this->userToAgent($config,$value['user_id']);
        }
    }

    private function number($config,$mall_id): void
    {
        $order = Db::name('order')
            ->field('user_id,count(0) AS count')
            ->where('mall_id',$mall_id)
            ->where('user_id', 'NOT IN', function ($sql) {
                $sql->name('user')
                    ->field('id')
                    ->where('agent_id', 'NOT NULL')
                    ->where('agent_id', '>', 0);
            })
            ->where('status', 4)
            ->group('user_id')
            ->select();
        foreach ($order as $key => $value) {
            if ($value['count'] < $config->become->condition->payOrder->orderCount) continue;
            $this->userToAgent($config,$value['user_id']);
        }
    }

    private function userToAgent($config,int $user_id): void
    {
        try {
            $user = Db::name('user')->find($user_id);
            $agent = Db::name('agent')
                ->where('user_id',$user['id'])
                ->find();
            if ($config->isAudit == 1) {
                $apply = Db::name('agent_apply')
                    ->where('user_id',$user['id'])
                    ->value('id');
                $data = $this->getAgentApplyData($user);
                if (!empty($apply))
                    Db::name('agent_apply')->where('id',$apply)->update($data);
                else
                    Db::name('agent_apply')->insert($data);
            }else{
                $data = $this->getAgentData($user);
                if (!empty($agent)) {
                    Db::name('agent')->where('user_id', $user['id'])->update($data);
                    $agent_id = $agent['id'];
                } else {
                    $agent_id = Db::name('agent')->insertGetId($data);
                }
                Db::name('agent_apply')
                    ->where('user_id',$user['id'])
                    ->update(['status' => 1]);
                Db::name('user')
                    ->where('id', $user_id)
                    ->update(['agent_id' => $agent_id]);
            }
            Db::commit();
        } catch (Exception $e) {
            Db::rollback();
        }
    }


    private function getAgentData($user){
        $data = [
            'user_id' => $user['id'],
            'mall_id' => $user['mall_id'],
            'name' => $user['nickname'],
            'mobile' => $user['mobile'],
            'pid' => $user['pid'],
            'apply_id' => 0,
            'status' => 1,
            'create_time' => date('Y-m-d H:i:s'),
            'update_time' => date('Y-m-d H:i:s'),
            'delete_time' => null
        ];
        return $data;
    }

    private function getAgentApplyData($user){
        $data = [
            'user_id' => $user['id'],
            'mall_id' => $user['mall_id'],
            'pid' => empty($user['pid']) ? 0 : $user['pid'],
            'name' => $user['nickname'],
            'mobile' => empty($user['mobile']) ? '' : $user['mobile'],
            'remark' => '满足条件自动申请',
            'status' => 0,
            'create_time' => date('Y-m-d H:i:s'),
            'update_time' => date('Y-m-d H:i:s'),
            'delete_time' => null
        ];
        return $data;
    }

    public function upAgent($mid)
    {
        $grades = Db::name("agent_grade")
            ->where("mall_id", $mid)
            ->where('status', 1)
            ->where('delete_time', null)
            ->order('id')
            ->select();
        foreach ($grades as $key => $grade) {
            $begin_id = $key == 0 ? 0 : $grades[$key-1]['id'];
            $agents = Db::name('agent')
                ->where('grade_id', ">=", $begin_id)
                ->where('grade_id', "<", $grade['id'])
                ->select();
            foreach ($agents as $ak => $agent) {
                // 下级用户人数
                if ($grade['users'] > 0) {
                    $users = Agent::getUsers($agent['id'], $mid);
                    $flag = $users >= $grade['users'] ? true : false;
                }
                // 佣金总额
                if ($grade['commission'] > 0) {
                    $commission = Agent::getCommissions($agent['id'], $mid);
                    $flag = $commission >= $grade['commission'] ? true : false;
                }
                // 已提现佣金总额
                if ($grade['draw'] > 0) {
                    $draw = Agent::getDraw($agent['user_id'], $agent['id'], $mid);
                    $flag = $draw >= $grade['draw'] ? true : false;
                }
                // 下级用户消费金额
                if ($grade['payment'] > 0) {
                    $payment = Agent::getPayment($agent['id'], $mid);
                    $flag = $payment >= $grade['payment'] ? true : false;
                }
                // 下级分销商人数
                if ($grade['agents'] > 0) {
                    $agents = Agent::getAgents($agent['id'], $mid);
                    $flag = $agents >= $grade['payment'] ? true : false;
                }
                if (isset($flag) && $flag) {
                    Db::name('agent')->where('id', $agent['id'])->update(['grade_id' => $grade['id']]);
                }
            }
        }
    }

    protected function executeAction(Input $input, Output $output)
    {
        // TODO: Implement executeAction() method.
        $list = Db::name('configuration')
            ->field('configuration,mall_id')
            ->where('type', 'agentExplain')
            ->select();
        foreach ($list AS $key => $value) {
            $config = json_decode($value['configuration']);
            if (isset($config->isUp) && $config->isUp == 1) {
                $this->upAgent($value['mall_id']);
            }
            if ($config->become->type == 4 || $config->become->type == 0 || $config->become->condition->buyCommodity->statistics == 0) continue;
            switch ($config->become->type) {
                case 1:
                    $this->commodity($config,$value['mall_id']);
                    break;
                case 2:
                    $this->money($config,$value['mall_id']);
                    break;
                case 3:
                    $this->number($config,$value['mall_id']);
                    break;
            }
        }
    }
}